import socket
import os
import sys
from sqlalchemy import create_engine, text

def test_network_connectivity(host, port=3306, timeout=5):
    """测试网络连通性"""
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(timeout)
        result = sock.connect_ex((host, port))
        sock.close()
        if result == 0:
            print(f"网络连通性测试成功: 能够连接到 {host}:{port}")
            return True
        else:
            print(f"网络连通性测试失败: 无法连接到 {host}:{port} (错误代码: {result})")
            return False
    except Exception as e:
        print(f"网络连通性测试出错: {e}")
        return False

def test_database_connection():
    """测试数据库连接"""
    host = "3o13.com"
    port = 3306
    
    print("开始测试服务器数据库连接...")
    print(f"目标主机: {host}:{port}")
    
    # 首先测试网络连通性
    if not test_network_connectivity(host, port):
        print("网络连通性测试失败，请检查:")
        print("1. 主机名是否正确")
        print("2. 防火墙是否允许出站连接到3306端口")
        print("3. 服务器防火墙是否允许入站连接到3306端口")
        print("4. MySQL是否在服务器上运行并监听3306端口")
        return False
    
    # 如果网络连通性测试通过，再测试数据库连接
    try:
        # 使用服务器的数据库URL进行测试
        database_url = 'mysql+pymysql://root:!Dd930308@3o13.com/svt_backend'
        engine = create_engine(database_url, connect_args={"connect_timeout": 10})
        
        print("正在尝试数据库连接...")
        # 测试连接
        with engine.connect() as connection:
            result = connection.execute(text("SELECT VERSION()"))
            version = result.fetchone()
            print("数据库连接成功!")
            print(f"MySQL版本: {version[0]}")
            return True
    except Exception as e:
        print(f"数据库连接测试失败: {e}")
        print("\n请检查:")
        print("1. MySQL用户权限设置")
        print("2. 数据库是否允许从你的IP地址连接")
        print("3. 用户名和密码是否正确")
        print("4. 数据库名称是否正确")
        return False

if __name__ == '__main__':
    test_database_connection()